<template>
  <div>
    <contact-summary-solt>
      <template slot="customerSlot">
        <customer-slot
          :customer="customer"
          :custType="'one'"
          :currentBusinessObj="currentBusinessObj"
          @requestUpdateCustInfo="handleRequestUpdateCustInfo"
          ></customer-slot>
      </template>
      <template slot="funTabSlot">
        <fun-tab-slot :tabs="tabs" :activeName="tabActiveName" :cdrCallInterfaceBtn="true" @handleEditTab="handleEditTab" @changeDetailTab="handlerChangeTab" :urlsStres="urlsStr" :isShowToolbar="true">
          <template slot="goldenSessionTab" v-if="showTabIntelligent ">
            <golden-session v-if="showTabIntelligent " :refresh = 'refresh' />
          </template>
          <template slot="businessTab">
            <business
              :busId="busId"
              :cid="cid"
              v-if="customer"
              :refresh="refresh"
              :showHistoryTable="true"
              :showbusRelatedTable="true"
              :custInfo="customer"
              v-on:event="businessEvent"
              :callInfo="callInfo"
              :cdrCall="true"
              :callId="id"
              :link="'call'"
              :businessNumbers="newRelatedCallList.ASSOCIATED_BUSINESSES"
              :linkData="buslinkData"></business>
          </template>
          <template slot="contactPlanTab">
            <contact-plan :refresh="refresh" :cid="cid"></contact-plan>
          </template>
          <template slot="historyTab">
            <contact-history :refresh="refresh" :cid="cid"></contact-history>
          </template>
          <template slot="changeLogTab">
            <operation-log v-if="this.$store.state.session.account.isSouthEastAsia !== 'true'" :refresh="refresh" :cid="cid"></operation-log>
          </template>
          <!--refresh.indexOf('item') > -1 当前的activeName是iframe才进行加载-->
          <template v-if="tabCount > 1" v-for= "item in tabUrls" :slot="item._id">
            <div :class="item.businesses && item.businesses.length > 0 ? 'moreIframe-wrap' : 'iframe-wrap'">
              <div v-if="item.businesses && item.businesses.length > 0" class="moreIframe-wrap">
                <div clss="businessesSelect" style="margin: 10px">业务类型</div>
                <el-select v-model="toolBarValue" filterable placeholder="请选择" style="margin: 0px 10px 10px">
                  <el-option
                    v-for="(toolBarItem, index) in item.businesses"
                    :key="index"
                    :label="toolBarItem.name"
                    :value="toolBarItem.url">
                  </el-option>
                </el-select>
                <iframe v-if="toolBarValue !== ''" :src="newUrl(toolBarValue)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
              </div>
              <iframe v-else :src="newUrl(item.url, item.isEncode)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
            </div>
          </template>
        </fun-tab-slot>
        <editTab :tabs="toolTabs" :type="'called'" ref="callTempTab" @updateTabConfig="updateTabConfig"></editTab>
      </template>
    </contact-summary-solt>
  </div>
</template>
<script>
  function getToken (store) {
    return store.dispatch('getToken')
  }
  // 此组件是来电合并&&添加客户
  import {isHasMenu, encrypt, getAesEncrypt, deepClone} from '@/utils/m7Utils'
  import editTab from '@/components/business-modules/webchat/webchat-right/customer-Information/dialog/editTab'
  import ContactSummarySolt from '@/components/public-modules/contact-summary/index.vue'
  import CustomerSlot from '@/components/public-modules/contact-summary/CustomerSlot'
  import FunTabSlot from '@/components/public-modules/contact-summary/FunTab'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  import ContactPlan from '@/components/public-modules/cust-tab-content/contact-plan/'
  import ContactHistory from '@/components/public-modules/cust-tab-content/contact-history/'
  import Business from '@/components/public-modules/cust-tab-content/business/'
  import GoldenSession from '@/components/public-modules/cust-tab-content/goldenSession'
  import customerApi from '@/store/api/customer'
  import bus from '@/store/eventBus'
  import * as globalTypes from 'src/store/mutation-types'
  export default {
    name: 'CdrCallSummary',
    data () {
      return {
        tabs: {
          normalTab: [
            {disabled: false, name: 'business', slotName: 'businessTab', labelName: this.$t('public.business')},
            {disabled: false, name: 'plan', slotName: 'contactPlanTab', labelName: this.$t('public.contactPlan')}
          ],
          tabUrl: {disabled: false}},
        tabActiveName: 'business',
        custType: '',
        toolbarTab: [],
        toolBarValue: '',
        busId: '',
        // newWindow: false, 经搜索没用上，稳定后可删除
        refresh: 'business',
        bussinessType: 'call',
        tabUrls: '',  // tab对接的url数据
        urlsStr: [], // tab对接弹出的url数据
        token: '', // 临时存储token数据，用于tab对接url拼接
        currentBusinessObj: {
          tabType: 'cdr_call',
          type: 'call',
          callId: this.$route.path.split('/')[4] || ''
        },
        // newBusiness: 0, 经搜索没用上，稳定后可删除
        tabCount: 1, // 控制tab对接页点开右侧时不加载，点击之后加载，加载之后再次切换不再重新加载资源,
        randomTime: 0,
        intelligentData: [],//金牌话术data
        tempTab: [],
        newRelatedCallList:{}
      }
    },
    props: {
      // 通话id
      id: {
        type: String,
        default: ''
      },
      // 客户ID
      //
      cid: {
        type: String,
        default: ''
      },
      callInfo: {type: Object, default: function () { return {} }},
      relatedCallList: {type: Object, default: function () { return {} }},
    },
    components: {
      ContactSummarySolt,
      CustomerSlot,
      FunTabSlot,
      Business,
      ContactPlan,
      ContactHistory,
      OperationLog,
      GoldenSession,
      editTab
    },
    computed: {
      transferNoInteligent(){
        return this.$store.state.call.transferNoInteligent
      },
      refreshBusRight () { // 点击卡片刷新右侧
        return this.$store.state.call.transCache.refreshCustRight
      },
      showIntelligent(){
        return this.$store.state.call.showIntelligent
      },
      showTabIntelligent(){
        if(this.showIntelligent && !this.transferNoInteligent){
          return true
        }else{
          return false
        }
      },
      customer () {
        return this.$store.state.call.current.cdr_call.currentSession[this.id] || null
      },
      // 通话提交工单增加的信息
      buslinkData () {
        let data = this.$parent.callInfo || {}
        if (data._id === this.id) {
          return {callNo: data.CALL_NO, callSheetId: data.CALL_SHEET_ID, offeringTime: data.OFFERING_TIME}
        }
        return {}
      },
      toolTabs () {
        let toolTabs = []
        let tabs = deepClone(this.tabs.normalTab)
        for (let i in tabs ) {
          toolTabs.push({...tabs[i]})
        }
        return toolTabs
      }
    },
    watch:{
      relatedCallList (newVal, oldVal) {
        this.newRelatedCallList = newVal
      }
    },
    methods: {
      isHaveMenu (func) {
        return isHasMenu(func, this.$store.state.session.user)
      },
      businessEvent (eventData) { // 工单操作事件外抛
        let data = eventData.data
        this.busId = data._id
        if (eventData.event !== 'changeBusinessMaster') {
          this.$store.dispatch('getBusinessDetailById', {_id: this.busId})
          this.getinfoData()
        }
        this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.cid)
        // 刷新新版工单左侧菜单栏数量统计
        this.$store.commit('business/REFRESH_MENUBAR', Math.random())
      },
      handlerChangeTab (tabName) { // tab切换
        this.tabActiveName = tabName
        this.refresh = tabName
        if (tabName === 'business') {
          this.busId = ''
        }
        if (tabName.indexOf('-') > -1) {
          this.tabCount += 1
        }
      },
      handleEditTab () {
        this.$refs.callTempTab.open()
      },
      updateTabConfig (val) {
        this.$store.dispatch('saveToolbarTabPosition', {module: 'call', tabs: val}).then(res => {
          this.tabs.normalTab = val
          this.intelligentData = val
          this.getTabUrl()
          if (this.refresh.indexOf('-') > -1) {
            this.tabCount = 2
          } else {
            this.tabCount = 1
          }
          bus.$emit('saveCallToolBar')
        })
      },
      getTabUrl () {
        let tabUrles = this.tabs.normalTab
        if (tabUrles && tabUrles.length > 0) { // 有tab对接的数据&&有获取token权限时才会去取token
          this.urlsStr = [] // 解决卡片切换之后不断地往里面push的问题
          if (this.$store.state.session.account.tokenCheck) {
            getToken(this.$store).then((token) => {
              this.token = token
              tabUrles.forEach(item => {
                this.urlsStr.push(this.newUrl(item.url ? item.url.replace('http://', '//') : ''))
              })
            })
          } else {
            tabUrles.forEach(item => {
              this.urlsStr.push(this.newUrl(item.url ? item.url.replace('http://', '//') : ''))
            })
          }
        }
      },
      fetchData () {
        return customerApi.queryCustomerInfo({_id: this.cid}).then(
          resp => {
            this.$store.commit('call/SET_READ', this.id)
            this.$store.commit('call/COUNT_UNREAD_CDR')
            this.$store.commit('call/SET_CUSTOMER_INFO', {data: resp.data, callSheetId: this.id})
            this.getTabUrl()
            if(!this.showTabIntelligent){
              this.tabs.normalTab = this.tabs.normalTab.filter(item=>{
                return item.name !== 'goldenSession'
              })
            }else{
              this.tabs.normalTab = this.intelligentData;
              let isExist = this.tabs.normalTab.some(item=>{
                if(item.name == 'goldenSession'){
                  return true
                }else{
                  return false
                }
              })
              if(!isExist){
                if(this.tempTab.length){
                  this.tabs.normalTab.unshift(this.tempTab[0])
                  this.updateTabConfig(this.tabs.normalTab)
                  this.loading = false
                }
              }
            }
          }
        )
      },
      handleRequestUpdateCustInfo (done) { // 点击修改客户归属的时候，刷新一下数据，避免A坐席修改归属之后，B坐席看到的还是旧的，直接覆盖A坐席的修改
        try {
          var promise = this.fetchData()
          if (!promise) {
            done()
          } else {
            promise.then(() => {
              this.$store.commit(globalTypes.UPDATE_CUSTOMER_INFO, {data: this.customer})
              done()
            })
          }
        } catch (error) {
          done()
        }
      },
      newUrl (url, isEncode) { // tab对接的数据处理
        let routes = this.$route.path.split('/')
        if (routes[2] !== 'call' || !routes[4]) { // 切换到其他模块或者是没有到详情的页面的时候，不传参
          return ''
        }
        let currentCustomer = this.customer
        if (url) {
          if (url.indexOf('?') === -1) {
            url += '?tabType=normal'
          } else {
            url += '&tabType=normal'
          }
        }
        let message = ''
        let shortTime = ''
        let callTabArr = window.sessionStorage.getItem('callTabParameter')
        callTabArr = callTabArr ? JSON.parse(callTabArr) : []
        let dataStr = ''
        for (let item in callTabArr) {
          if (this.id === callTabArr[item].id) {
            let itemObj = callTabArr[item].data
            for (let item2 in itemObj) {
              if (item2 === 'REPEAT_CALL') {
                continue
              }
              if (item2 === 'offeringTime') {
                shortTime = itemObj[item2].substring(11) || ''
              }
              dataStr += item2 + '=' + itemObj[item2] + '&'
            }
            break
          }
        }
        message += '&' + dataStr
        message += '&shortTime=' + shortTime + '&loginName=' + this.$store.state.session.user.loginName +
          '&exten=' + this.$store.state.session.user.exten + '&displayName=' + this.$store.state.session.user.displayName
        if (currentCustomer) { // 定位到客户
          let custTmpls = this.$getCache('custTmpls')
          let custStatusName = custTmpls[0].status[currentCustomer.status] || ''
          if (custTmpls && custTmpls.length > 0 && custTmpls[0].template_type !== 'company') { // 个人版
            message += '&name=' + (currentCustomer.name || '') + '&status=' + (custStatusName || '') + '&title=' + (currentCustomer.title || '') + '&phone=' + this.arrToStr(currentCustomer.phone, 'tel') + '&email=' + this.arrToStr(currentCustomer.email, 'email') +
                    '&weixin=' + this.arrToStr(currentCustomer.weixin, 'num') + '&province=' + (currentCustomer.province || '') + '&city=' + (currentCustomer.city || '') + '&note=' + (currentCustomer.note || '') +
                    '&sex=' + (currentCustomer.sex || '') + '&age=' + (currentCustomer.age || '') + '&birth=' + (currentCustomer.birth || '')
          } else { // 企业版
            message += '&name=' + (currentCustomer.name || '') + '&status=' + (custStatusName || '') + '&title=' + (currentCustomer.title || '') + '&phone=' + this.arrToStr(currentCustomer.phone, 'tel') + '&email=' + this.arrToStr(currentCustomer.email, 'email') +
                    '&weixin=' + this.arrToStr(currentCustomer.weixin, 'num') + '&province=' + (currentCustomer.province || '') + '&city=' + (currentCustomer.city || '') + '&note=' + (currentCustomer.note || '') +
                    '&web=' + (currentCustomer.web || '')
          }
        }
        if (url && (url.indexOf('power.7moor.com') > -1 || url.indexOf('power-') > -1)) {
          if (this.$store.state.session.sessionId && window.sessionStorage.getItem('loginToken')) {
            message += '&sessionId=' + this.$store.state.session.sessionId + '&loginToken=' + window.sessionStorage.getItem('loginToken')
          }
        }
        const account = this.$store.state.session.account
        message += '&accountId=' + account.account
        if (account.tokenCheck) {
          message += '&token=' + (this.token.token || '') + '&tokenId=' + (this.token.tokenId || '')
        }
        if (account.encryptionCheck && account.encryType === 'aes') { // 开启隐私加密 && aes加密
          message += `&${account.aesOffsetKey || 'iv'}=${account.aesOffsetValue}`
        }
        if (message.indexOf('#') !== -1) {
          message = message.replace(/#/g, '%23')
        }
        url += message
        if (isEncode) {
          url = encodeURI(url)
        }
        return url.replace('http://', '//').replace('${customerId}', currentCustomer ? currentCustomer._id : '')
      },
      arrToStr (arr, field) {
        let account = this.$store.state.session.account
        let encryptionCheck = account.encryptionCheck
        if (!Array.isArray(arr)) {
          return ''
        }
        let str = ''
        for (let i = 0; i < arr.length; i++) {
          if (encryptionCheck && field === 'tel') {
            if (account.encryType === 'aes') { // aes加密
              str += getAesEncrypt(account.aesSecret, account.aesOffsetValue, arr[i][field]) + ','
            } else { // 默认加密
              let secretKey = account.secretKey
              str += encrypt(secretKey, arr[i][field]) + ','
            }
          } else {
            str += arr[i][field] + ','
          }
        }
        if (str.indexOf(',') !== -1) {
          str = str.substring(0, str.lastIndexOf(','))
        }
        return str
      },
      queryToolbarFun (callback) {
        let p1 = this.$store.dispatch('queryToolbarTabPosition', {module: 'call'})
        let p2 = this.$store.dispatch('getCache', {type: 'tabUrlAddress'}) // tab对接
        Promise.all([p1, p2]).then(([res]) => {
          if (res && res.data) {
            let normalTab = []
            let list = res.data || []
            let toolbarTabArr = []
            for (let i = 0; i < list.length; i++) {
              if ('show' in list[i] && !list[i].show) {
                continue
              }
              if (list[i].businesses || list[i].url) {
                toolbarTabArr.push(list[i])
                if ('editable' in list[i]) {
                  normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, type: 'toolbar'})
                } else {
                  normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, url: list[i].url, isEncode: list[i].isEncode})
                }
              } else {
                if (list[i].tabName === 'history') {
                  if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_contact_history')) {
                    normalTab.push({disabled: false, name: 'history', slotName: 'historyTab', labelName: this.$t('public.history'), _id: list[i]._id})
                  }
                } else if (list[i].tabName === 'changeLog') {
                  if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_operation_log')) {
                    if (this.$store.state.session.account.isSouthEastAsia !== 'true') {
                      normalTab.push({
                        _id: list[i]._id,
                        disabled: false,
                        name: 'changeLog',
                        slotName: 'changeLogTab',
                        labelName: this.$t('public.changeLog')
                      })
                    }
                  }
                } else if (list[i].tabName === 'contactPlan') {
                  normalTab.push({_id: list[i]._id, disabled: false, name: 'plan', slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
                } else if (list[i].tabName === 'callDetail') {
                  normalTab.splice(i, 1)
                } else {
                  if (list[i].tabName) {
                    normalTab.push({_id: list[i]._id, disabled: false, name: list[i].tabName, slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
                  }
                }
              }
            }
            this.toolbarTab = toolbarTabArr
            this.tabs.normalTab = normalTab
            if(!this.showTabIntelligent){
              this.tabs.normalTab = this.tabs.normalTab.filter(item=>{
                return item.name !== 'goldenSession'
              })
            }
            this.intelligentData = deepClone(normalTab)
            this.tempTab = this.intelligentData.filter(item=>{
              return item.name == 'goldenSession'
            })
            this.tabActiveName = this.tabs.normalTab[0].slotName ? this.tabs.normalTab[0].name : this.tabs.normalTab[0]._id
            this.refresh = this.tabs.normalTab[0].slotName ? this.tabs.normalTab[0].name : this.tabs.normalTab[0]._id
            if (this.refresh.indexOf('-') > -1) {
              this.tabCount = 2
            } else {
              this.tabCount = 1
            }
          }
          this.tabUrls = this.toolbarTab
          if (callback) {
            callback()
          }
        })
      },
      // 获取通话信息
      async getinfoData(){
        let data = {
            CALL_SHEET_ID: this.callInfo._id,
            autoqc: true
        }
        await this.$store.dispatch('queryCallList', data).then((res) => {
          if (res && res.list && res.list.length) {
            this.newRelatedCallList = res.list[0]
          } else {
            this.newRelatedCallList = {}
          }
        })
      }
    },
    activated(){
      this.queryToolbarFun()
    },
    beforeMount () {
      bus.$on('saveCallToolBar', () => {
        this.queryToolbarFun()
      })
      this.queryToolbarFun(() => {
        this.fetchData()
      })
      this.getinfoData()
    },
    beforeDestroy () {
      bus.$off('saveCallToolBar')
    }
  }
</script>
<style lang="stylus" scoped>
  .iframe-wrap
    height calc(100vh - 54px)
  iframe
    height 100%
    width 100%
</style>
